package com.lap.framework.junit.application.builder;

import com.lap.framework.junit.configure.EnvConfigure;
import com.lap.framework.junit.configure.model.FileConfigure;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;

@Slf4j
public class JavaFileScanner {

  public List<File> scanJavaFiles(EnvConfigure configure, File parent) {
    List<File> javaFiles = new ArrayList<>();

    File[] files = parent.listFiles();
    if (files == null) {
      log.warn("No files found in directory: {}", parent.getAbsolutePath());
      return javaFiles;
    }

    Arrays.stream(files).filter(file -> isJavaSourceFile(configure, file)).forEach(javaFiles::add);

    return javaFiles;
  }

  private boolean isJavaSourceFile(EnvConfigure env, File file) {
    if (!FilenameUtils.getExtension(file.getName()).equalsIgnoreCase("java")) {
      return false;
    }

    FileConfigure fileConfig = env.getFileConfigure();
    return fileConfig.isAll() || fileConfig.getFileList().contains(file.getName());
  }
}
